package org.molamil.acto.handlers {
	import org.molamil.acto.params.ParamsParser;
	import org.molamil.acto.core.Context;
	import org.molamil.acto.utils.StringUtils;
	import org.molamil.acto.core.loggers.Logger;

	/**
	 * @author Jorge Hernandez
	 */
	public class HandlersParser {
		
		
		// CONSTANTS
		
		private static const log:Logger = Logger.getLogger("HandlerParser");
		
		
		// PROPERTIES
		protected var xml:XML;
		
		
		// CONSTRUCTOR
		
		public function HandlersParser() {
			// Empty.
		}

		
		// PUBLIC METHODS
		
		public function parse(xml:XML, context:Context):Array { // of HandlerContext
			
			log.info("parse()");
			
			this.xml = xml;
		
			// Create the arrays.
			var handlers:Array = new Array();
			
			// Get handlers.
			var handlerNodes:XMLList = xml.handler;
			
			// Iterate the handlers.
			for each (var handlerNode:XML in handlerNodes) {
				
				var handlerContext:HandlerContext = new HandlerContext();
				
				handlerContext.type = StringUtils.trim(handlerNode.attribute("type"));
				if (handlerContext.type == "")
					handlerContext.type = null;
				
				handlerContext.className = StringUtils.trim(handlerNode.attribute("class"));
				if (handlerContext.className == "")
					handlerContext.className = null;
				
				handlerContext.source = StringUtils.trim(handlerNode.attribute("source"));
				if (handlerContext.source == "")
					handlerContext.source = null;
				
				handlerContext.action = StringUtils.trim(handlerNode.attribute("action"));
				if (handlerContext.action == "")
					handlerContext.action = null;
				
				handlerContext.priority = int(StringUtils.trim(handlerNode.attribute("priority")));
				if (isNaN(handlerContext.priority))
					handlerContext.priority = 0;
					
				//XXX: Make this configurable.
				handlerContext.params = new ParamsParser().parse(handlerNode);
				
				handlerContext.context = context;
					
				handlers.push(handlerContext);
				
			}
			
			return handlers;
			
		}
		
		
	}
}
